<?php


namespace Modules\Common\General\Security\Authorization\Concerns;


use Modules\Common\General\Security\Authorization\Casbin;
use Modules\Common\Models\AdminPermission;
use Modules\Common\Models\Branch;

trait ManagePermission
{
    public function deletePermission(int $permissionId,int $branchId)
    {
        return Casbin::deletePermission("p$permissionId","b$branchId");
    }

    protected function permissionsForPresentation(array $permissions){
        return $this->permissions2Record($this->filterVirtualPermissions($permissions));
    }


    protected function filterVirtualPermissions(array $permissions)
    {
        foreach ($permissions as $k => $item) {
            if (in_array('-', $item)) {
                unset($permissions[$k]);
            }
        }
        return array_values($permissions);
    }

    protected function permissions2Record($permissions)
    {
        $arr = [];
        foreach ($permissions as $permission) {
            $permissionId = substr($permission[1], 1);
            $branchId = substr($permission[2], 1);
            $permissionName = AdminPermission::whereKey($permissionId)->value('name');
            $branchName = Branch::whereKey($branchId)->value('branch_name');
            $arr[] = [
                'branch_id' => $branchId,
                'branch_name' => $branchName,
                'permission_id' => $permissionId,
                'permission_name' => $permissionName
            ];
        }
        return $arr;
    }

}
